package com.tj.jinzao.fragment;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.tj.jinzao.R;
import com.tj.jinzao.activity.LoginActivity;
import com.tj.jinzao.api.ApiRetrofit;
import com.tj.jinzao.api.ApiService;
import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BaseFragment;
import com.tj.jinzao.callback.IRegisterLoginView;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.model.User;
import com.tj.jinzao.presenter.RegisterLoginPresenter;
import com.tj.jinzao.utils.ToastUtils;
import com.tj.jinzao.utils.Utils;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

import static com.tj.jinzao.activity.LoginActivity.LOGIN_TYPE_VERITY_LOGIN;

/**
 * 绑定手机
 * Created by wjy on 2019/1/5.
 */
public class BindPhoneFragment extends BaseFragment<RegisterLoginPresenter> implements IRegisterLoginView<User> {

    @BindView(R.id.et_password)
    EditText mPasswordView;
    @BindView(R.id.et_phone)
    EditText mPhoneEditText;
    @BindView(R.id.et_code)
    EditText mCodeEditText;
    @BindView(R.id.iv_see)
    ImageView mSeeView;
    @BindView(R.id.sendSMS)
    TextView sendSMS;

    private int mType;//1设置密码，2重置密码
    private String mOpenId;

    public static BindPhoneFragment newInstance() {
        return new BindPhoneFragment();
    }
    private int postion=0;
    protected ApiService mApiService = ApiRetrofit.getInstance().getApiService();

    private CompositeSubscription mCompositeSubscription;


    public void detachView() {
        onUnsubscribe();
    }

    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 101:
                    postion--;
                    if(postion<=0){
                        sendSMS.setText("发送验证码");
                        return;
                    }
                    sendSMS.setText(String.valueOf(postion)+"s");
                    break;
                case 102:
                    break;
                case 103:
                    break;
            }
        }
    };
    private Timer timer=null;
    private TimerTask timerTask=null;
    @Override
    public void onDestroy() {
        super.onDestroy();
        detachView();
        if(timerTask!=null){
            timerTask.cancel();
            timerTask=null;
        }
        if(timer!=null){
            timer.cancel();
            timer=null;
        }
    }

    public void send(){
        if(postion<=0){
            if(TextUtils.isEmpty(mPhoneEditText.getText())){
                ToastUtils.showToast(getActivity(),"请输入手机号");
            }else if(Constant.isMobileNO(mPhoneEditText.getText().toString())){
                addSubscription(mApiService.sendCode(mPhoneEditText.getText().toString().trim(), "bind"), new SubscriberCallBack<Boolean>(getActivity()) {
                    @Override
                    protected void onSuccess(Boolean response) {
                        ToastUtils.showToast(getActivity(),"验证码发送成功");
                        postion=60;
                        if(timer==null){
                            timer=new Timer();
                            timerTask=new TimerTask() {
                                @Override
                                public void run() {
                                    handler.sendEmptyMessage(101);
                                }
                            };
                            timer.schedule(timerTask,100,1000);
                        }


                    }

                    @Override
                    protected void onFailure(ResultResponse response) {
                    }

                    @Override
                    protected boolean isShowProgress() {
                        return true;
                    }
                });
            }else {
                ToastUtils.showToast(getActivity(),"手机号格式错误");
            }

        }

    }

    @OnClick(R.id.iv_see)
    public void showPassword() {

        if (EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD == mPasswordView.getInputType()) {
            //如果不可见就设置为可见
            mPasswordView.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
            mPasswordView.setTransformationMethod(PasswordTransformationMethod.getInstance());
            mSeeView.setImageResource(R.mipmap.login_unsee);
        } else {
            //如果可见就设置为不可见
            mPasswordView.setInputType(EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            mPasswordView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            mSeeView.setImageResource(R.mipmap.login_see);
        }
        //执行上面的代码后光标会处于输入框的最前方,所以把光标位置挪到文字的最后面
        mPasswordView.setSelection(mPasswordView.getText().toString().length());
    }

    @Override
    protected RegisterLoginPresenter createPresenter() {
        return new RegisterLoginPresenter(this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_bind_phone;
    }

    @OnClick(R.id.bt_submit)
    public void submit() {
        String psd = mPasswordView.getText().toString().trim();
        String phone = mPhoneEditText.getText().toString().trim();
        String code = mCodeEditText.getText().toString().trim();
        if (!Utils.isPhone(phone)) {
            ToastUtils.showToast(mContext, "请输入正确手机号");
        }else if (TextUtils.isEmpty(code) || code.length()!= 4) {
            ToastUtils.showToast(mContext, "请输入4位验证码");
        }else if (TextUtils.isEmpty(psd)) {
            ToastUtils.showToast(mContext, "请输入密码");
        } else if ((psd.length() < 6 || psd.length() > 18)) {
            ToastUtils.showToast(mContext, "密码为6-18位字母或数字");
        } else {
            mPresenter.bindPhone(phone,code,psd,getActivity(),getActivity().getIntent().getIntExtra("typeLogin",0));
        }

    }
    @OnClick(R.id.iv_back)
    public void back(){
      ((LoginActivity) mContext).switchFragment(LOGIN_TYPE_VERITY_LOGIN);
    }


    @OnClick(R.id.sendSMS)
    public void setSendSMS(){
        send();
    }

    @Override
    public void onRequestSuccess(User user) {
//          if(getActivity().getIntent().getIntExtra("typeLogin",0)==6){
//              getActivity().finish();
//          }
//        UserManager.getInstance().saveUserData(user);
//        startActivity(new Intent(getActivity(), CompleteInfoActivity.class));

    }

    @Override
    public void onRequestNoData(String message) {

    }

    @Override
    public void onRequestError(String error_message) {
        if(error_message.equals("SUCCESS")){
            return;
        }
        ToastUtils.showToast(getActivity(),error_message);
    }

    @Override
    public void onGetCodeSuccess(String s) {
        //发送验证码成功，此处不用
    }

    @Override
    public void onGetCodeFailed(String reason) {
        //发送验证码失败，此处不用
    }

    @Override
    public void onCheckCodeSuccess(String token) {
        //验证码通过
    }
}
